<template>
  <px-button
    v-if="drawerType === 'execute' && [0, 1, 3].includes(detailData.workOrderStatus) && detailData.isExecutor"
    :disabled="recordList.length >= 5"
    style="margin-top: 16px"
    type="primary"
    @click="handleAdd"
  >
    新增维修记录
  </px-button>
  <px-scrollbar height="calc(100vh - 410px)" class="equip-wrap-common">
    <EditDropDown
      v-for="(item, index) in recordList"
      :id="`record${index}`"
      ref="dropDown"
      :key="item.id"
      :dropdownTitle="`维修记录${enumList[index]}`"
    >
      <template v-if="drawerType === 'execute' && [0, 1, 3].includes(detailData.workOrderStatus) && detailData.isExecutor" v-slot:btn>
        <px-button v-if="item.createBy === userInfo.userId && !item.isEdit" link type="primary" @click="handleEdit(index)"> 编辑 </px-button>
        <px-button v-if="item.isEdit" link type="primary" @click="handleSave(formRef, index)">保存</px-button>
        <px-button v-if="item.isEdit" link type="primary" @click="handleCancel(index)">取消</px-button>
      </template>
      <template v-slot:content>
        <px-form v-if="item.isEdit" ref="formRef" style="width: 100%" :model="formValue" :rules="rules" label-position="right" label-width="140px">
          <px-row>
            <px-col :span="12">
              <px-form-item label="维修开始时间" prop="acceptTime">
                <px-date-picker
                  v-model="formValue.acceptTime"
                  format="YYYY-MM-DD HH:mm"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  type="datetime"
                  :disabled-date="disabledDate"
                  placeholder="请选择维修开始时间"
                  style="width: 100%"
                />
              </px-form-item>
            </px-col>
          </px-row>
          <px-row>
            <px-col :span="12">
              <px-form-item label="维修人" prop="executorName">
                <px-input v-model="formValue.executorName" style="width: 100%" disabled placeholder="自动生成" maxlength="50" />
              </px-form-item>
            </px-col>
          </px-row>
          <px-row>
            <px-col :span="24">
              <px-form-item label="照片上传" prop="faultImageList">
                <PhotoUpload
                  photoType="add"
                  :photoData="{ moduleName: moduleName }"
                  :photoList="formValue.faultImageList"
                  style="margin-bottom: 18px"
                  @changePhotoList="changePhotoList"
                  @savePhotoStatus="savePhotoStatus"
                />
              </px-form-item>
            </px-col>
          </px-row>
          <px-row style="width: 100%">
            <px-col :span="12">
              <px-form-item label="是否更换备件" prop="isChange">
                <px-radio-group v-model="formValue.isChange" style="width: 100%" @change="handleSpareChange">
                  <px-radio :label="1">是</px-radio>
                  <px-radio :label="0">否</px-radio>
                </px-radio-group>
              </px-form-item>
            </px-col>
          </px-row>
          <px-row v-if="isSpare === 1">
            <px-col :span="12">
              <div style="display: flex">
                <px-form-item label="关联出库单" prop="sparePartOutNum">
                  <px-input v-model="formValue.sparePartOutNum" disabled placeholder="根据所选单号获取" maxlength="50" />
                </px-form-item>
                <px-button style="margin-left: 8px" type="primary" plain @click="isOutBoundShow = true">选择</px-button>
              </div>
            </px-col>
          </px-row>
          <px-row v-if="isSpare === 1">
            <px-col :span="12">
              <px-form-item label="">
                <px-button type="primary" plain :disabled="formValue.sparePartOutNum !== ''" @click="isSpareShow = true">备件申请</px-button>
              </px-form-item>
            </px-col>
          </px-row>
          <px-row v-if="isSpare === 1">
            <px-col :span="24">
              <px-form-item label="">
                <px-table
                  :data="formValue.sparePartInventoryDTOList"
                  class="equip-table"
                  size="small"
                  max-height="400"
                  border
                  @selection-change="selectionChange"
                >
                  <px-table-column type="selection" min-width="40" align="center" />
                  <px-table-column type="index" label="序号" width="50" show-overflow-tooltip />
                  <px-table-column
                    v-for="(item, index) in spareTableColumns"
                    :key="index"
                    :label="item.label"
                    :min-width="item.minWidth"
                    :align="item.align"
                    :show-overflow-tooltip="item.showOverflowTooltip"
                    :fixed="item.fixed"
                  >
                    <template #default="scope">
                      {{ scope.row[item.prop] === 0 ? scope.row[item.prop] : scope.row[item.prop] ? scope.row[item.prop] : "-" }}
                    </template>
                  </px-table-column>
                  <px-table-column label="实际使用数量" min-width="140">
                    <template #default="scope">
                      <px-input-number v-model="scope.row.usedQuantity" :max="scope.row.quantity" :min="0" />
                    </template>
                  </px-table-column>
                </px-table>
                <div
                  v-if="formValue.sparePartInventoryDTOList?.length !== 0"
                  style="
                    display: flex;
                    align-items: center;
                    justify-content: space-between;
                    width: 100vw;
                    height: 40px;
                    padding: 0 12px 0 16px;
                    margin: -6px 0 16px;
                    background: #ecf5ff;
                    border-radius: 4px;
                  "
                >
                  <div style="font-size: 14px; color: rgb(0 0 0 / 80%)">
                    已选<span style="color: #3b82f6">{{ selectIds.length }}</span>
                  </div>
                  <div>
                    <span>设置填写使用数量</span>
                    <px-input-number
                      v-model.number="quantityNumber"
                      style="margin-left: 20px"
                      :min="0"
                      size="small"
                      :disabled="selectIds.length === 0"
                      @change="batchSetQuantityNumber"
                    />
                  </div>
                </div>
              </px-form-item>
            </px-col>
          </px-row>
          <px-row>
            <px-col :span="24">
              <px-form-item label="维修检查内容上传" prop="maintenanceMaterialList">
                <FileUpload
                  fileType="edit"
                  :countLimit="10"
                  fileTypeValue="图片、Word等"
                  :fileData="{ moduleName: moduleName }"
                  :fileList="formValue.maintenanceMaterialList"
                  style="margin-bottom: 18px"
                  @changeFileList="changeFileList"
                  @saveFileStatus="saveFileStatus"
                />
              </px-form-item>
            </px-col>
          </px-row>
          <px-row>
            <px-col :span="24">
              <px-form-item label="维修描述" prop="faultCause">
                <px-input
                  v-model="formValue.faultCause"
                  type="textarea"
                  placeholder="请输入维修描述"
                  :autosize="{ minRows: 2, maxRows: 4 }"
                  maxlength="1000"
                  clearable
                />
              </px-form-item>
            </px-col>
          </px-row>
        </px-form>
        <div v-else>
          <div class="view-order-item">
            <div class="title">维修开始时间：</div>
            <div class="content">{{ item.acceptTime }}</div>
          </div>
          <div class="view-order-item">
            <div class="title">维修人：</div>
            <div class="content">{{ item.executorName }}</div>
          </div>
          <div class="view-order-item">
            <div class="title">照片：</div>
            <div class="content">
              <PhotoUpload photoType="view" :photoData="{ moduleName: moduleName }" :photoList="item.faultImageList || []" />
            </div>
          </div>
          <div class="view-order-item">
            <div class="title">是否更换备件：</div>
            <div class="content">{{ item.sparePartOutNum ? "是" : "否" }}</div>
          </div>
          <div v-if="item.sparePartOutNum" class="view-order-item">
            <div class="title">关联出库单：</div>
            <div class="content" style="color: #3b82f6; cursor: pointer" @click="handleToSpare(item.sparePartOutId)">{{ item.sparePartOutNum }}</div>
          </div>
          <div v-if="item.sparePartOutNum" class="view-order-item">
            <div class="title" />
            <div class="content">
              <px-table :data="item.sparePartInventoryDTOList" class="equip-table" size="small" max-height="400" border>
                <px-table-column type="index" label="序号" width="50" show-overflow-tooltip fixed />
                <px-table-column
                  v-for="(item, index) in spareTableColumns"
                  :key="index"
                  :label="item.label"
                  :min-width="item.minWidth"
                  :align="item.align"
                  :show-overflow-tooltip="item.showOverflowTooltip"
                  :fixed="item.fixed"
                >
                  <template #default="scope">
                    {{ scope.row[item.prop] === 0 ? scope.row[item.prop] : scope.row[item.prop] ? scope.row[item.prop] : "-" }}
                  </template>
                </px-table-column>
                <px-table-column prop="usedQuantity" label="实际使用数量" min-width="120" show-overflow-tooltip />
              </px-table>
            </div>
          </div>
          <div class="view-order-item">
            <div class="title">维修检查内容：</div>
            <div class="content">
              <FileUpload fileType="view" :fileData="{ moduleName: moduleName }" :fileList="item.maintenanceMaterialList" />
            </div>
          </div>
          <div class="view-order-item">
            <div class="title">维修描述：</div>
            <div class="content">{{ item.faultCause }}</div>
          </div>
        </div>
      </template>
    </EditDropDown>
    <!--备件申请弹窗-->
    <px-dialog v-model="isSpareShow" title="选择备件" width="1200px" destroy-on-close append-to-body @open="handleOpen">
      <AddSparePartsDetail
        :isMain="isMain"
        :isView="isView"
        :drawerType="'maintain'"
        :maintainData="detailData"
        :userId="userInfo.userId"
        :username="userInfo.username"
        @backMainPage="backCurrentPage"
      />
    </px-dialog>
    <SpareList :visible="isOutBoundShow" :facCode="detailData.facCode" @closeDialog="closeOutBoundDialog" />
  </px-scrollbar>
</template>
<script setup lang="ts">
import { addRecord, editRecord, getRecordList } from "@/api/erc/maintain";
import { getInventoryOut } from "@/api/erc/spareParts";
import FileUpload from "@/components/Upload/FileUpload.vue";
import PhotoUpload from "@/components/Upload/PhotoUpload.vue";
import EditDropDown from "@/views/all/equip/components/EditDropDown.vue";
import dayjs from "dayjs";
import { nextTick } from "process";
import { PxMessage, PxMessageBox } from "px-ui";
import { computed, reactive, ref, toRefs, watchEffect } from "vue";
import { useRouter } from "vue-router";
import AddSparePartsDetail from "../../spareParts/outbound/components/AddSparePartsDetail.vue";
import SpareList from "./SpareList.vue";

const router = useRouter();

const handleOpen = () => {
  isMain.value = false;
  isView.value = false;
};

// 调用父级-返回主页、查询列表方法
const emits = defineEmits(["handleRecordInfo"]);
// 父级传过来的值
const props = defineProps(["activeName", "userInfo", "moduleName", "detailData", "drawerType"]);

// 页面本身的值
const formRef = ref();
const state = reactive<any>({
  isMain: true, // 主页面true 详情页面false
  isView: true, // 查看true 新增/编辑false
  formValue: {
    sparePartOutNum: ""
  },
  isSpare: undefined,
  photoStatusFlag: false,
  recordList: [],
  spareTableColumns: [
    { prop: "facCodeDesc", label: "所属地块", minWidth: "80", showOverflowTooltip: true, fixed: true },
    { prop: "sparePartName", label: "备件名称", minWidth: "100", showOverflowTooltip: true },
    { prop: "eqpTypeCodeDesc", label: "备件类型", minWidth: "100", showOverflowTooltip: true },
    { prop: "specification", label: "规格型号", minWidth: "100", showOverflowTooltip: true },
    { prop: "brandVal", label: "品牌", minWidth: "100", showOverflowTooltip: true },
    { prop: "sparePartUnit", label: "单位", minWidth: "60", showOverflowTooltip: true },
    { prop: "currentStock", label: "当前库存", minWidth: "80", showOverflowTooltip: true },
    { prop: "quantity", label: "本次出库数量", minWidth: "110", showOverflowTooltip: true }
  ],
  fileStatusFlag: false,
  isSpareShow: false,
  isOutBoundShow: false,
  selectIds: [],
  quantityNumber: undefined
});

const {
  isMain,
  isView,
  formValue,
  photoStatusFlag,
  isSpare,
  spareTableColumns,
  fileStatusFlag,
  recordList,
  isSpareShow,
  isOutBoundShow,
  selectIds,
  quantityNumber
} = toRefs(state);
// 表单校验规则
const rules = computed(() => ({
  acceptTime: [{ required: true, message: "维修开始时间不能为空", trigger: "blur" }],
  isChange: [{ required: true, message: "请选择是否更换备件", trigger: "blur" }]
}));

const enumList = {
  0: "一",
  1: "二",
  2: "三",
  3: "四",
  4: "五"
};

const isCanEdit = defineModel("isCanEdit", { type: Boolean, default: true });
const lengthOfRecord = defineModel("lengthOfRecord", { type: Number });

const getList = async () => {
  const res = await getRecordList(props.detailData.id);
  recordList.value = res || [];
  lengthOfRecord.value = recordList.value.length;
};

watchEffect(() => {
  if (props.activeName === "second") {
    getList();
  }
});

const disabledDate = (time: Date) => {
  return time.getTime() < Date.now() - 8.64e7;
};

// 新的图片列表
const changePhotoList = val => {
  console.log(val);
  formValue.value.faultImageList = val;
};
// 图片是否上传完，是否可以保存
const savePhotoStatus = val => {
  photoStatusFlag.value = val;
};

// 新的文件列表
const changeFileList = val => {
  formValue.value.maintenanceMaterialList = val;
};
// 文件是否上传完，是否可以保存
const saveFileStatus = val => {
  fileStatusFlag.value = val;
};

const handleSpareChange = val => {
  isSpare.value = val;
  if (val === 0) {
    formValue.value.sparePartOutNum = "";
    formValue.value.sparePartInventoryDTOList = [];
  }
};

// 表格多选框选中-批量删除使用
const selectionChange = (val: any) => {
  selectIds.value = [];
  val.forEach((item: any) => {
    if (item.id) {
      selectIds.value.push(item.id);
    }
  });
  quantityNumber.value = 0;
};

// 批量设置number
const batchSetQuantityNumber = () => {
  selectIds.value.forEach(val => {
    formValue.value.sparePartInventoryDTOList?.forEach((v, i) => {
      if (val === v.id) {
        v.usedQuantity = quantityNumber.value;
      }
    });
  });
};
const handleAdd = () => {
  if (!isCanEdit.value) {
    PxMessage.warning("当前有正在进行编辑的维修记录");
    return;
  }
  isCanEdit.value = false;
  recordList.value.push({
    isEdit: true
  });
  formValue.value.executorId = props.userInfo.userId;
  formValue.value.executorName = props.userInfo.realName;
  formValue.value.sparePartOutNum = "";
  formValue.value.acceptTime = dayjs().format("YYYY-MM-DD HH:mm:ss");
  const len = recordList.value?.length;
  nextTick(() => {
    document.getElementById(`record${len - 1}`)?.scrollIntoView({
      behavior: "smooth"
    });
  });
};

// 拉取设备关联备件
const getRelationSpareParts = async () => {
  // formValue.value.sparePartInventoryDTOList = await getInventoryOut(formValue.value.sparePartOutNum);

  const sparePartInventoryDTOList = (await getInventoryOut(formValue.value.sparePartOutNum)) || [];
  formValue.value.sparePartInventoryDTOList = sparePartInventoryDTOList.map(item => ({ ...item, usedQuantity: null }));
};

const closeOutBoundDialog = (val?: any) => {
  isOutBoundShow.value = false;
  if (val) {
    const { outNum } = val;
    formValue.value.sparePartOutNum = outNum;
    getRelationSpareParts();
  }
};

const handleToSpare = id => {
  router.push(`/erc/spareParts/outbound?id=${id}`);
};

const backCurrentPage = val => {
  isSpareShow.value = false;
  if (val) {
    formValue.value.sparePartOutNum = val;
    getRelationSpareParts();
  }
};

const dropDown = ref();

const handleEdit = index => {
  if (isCanEdit.value === false) {
    PxMessage.warning("只能同时编辑一行");
    return;
  }
  dropDown.value[index]?.openDown();
  isCanEdit.value = false;
  const { sparePartOutNum, maintenanceMaterialList, faultImageList } = recordList.value[index];
  if (sparePartOutNum) {
    isSpare.value = sparePartOutNum ? 1 : 0;
  }
  formValue.value = {
    ...recordList.value[index],
    isChange: sparePartOutNum ? 1 : 0,
    maintenanceMaterialList: maintenanceMaterialList || [],
    faultImageList: faultImageList || []
  };
  recordList.value[index].isEdit = true;
};
// 保存维修记录
const handleSave = async (formEl, index) => {
  console.log(formRef.value);
  if (!formEl) return;
  await formEl[0].validate(async valid => {
    if (valid) {
      const { id, sparePartInventoryDTOList, isChange, sparePartOutNum, maintenanceMaterialList, faultImageList } = formValue.value;
      if (isChange && !sparePartOutNum) {
        PxMessage.warning("请选择关联的出库单号");
        return;
      }
      isCanEdit.value = true;
      // 处理备件出入库数量
      const inventoryDetailList = [];
      if (sparePartInventoryDTOList?.length !== 0) {
        sparePartInventoryDTOList?.forEach(item => {
          inventoryDetailList.push({
            parePartId: item.id,
            quantity: item.usedQuantity
          });
        });
      }
      // 处理照片数据
      const pictureList = [];
      if (faultImageList && faultImageList.length > 0) {
        faultImageList.forEach(item => {
          if (item?.id) {
            pictureList.push(item.id);
          } else if (item?.response.data.id) {
            pictureList.push(item.response.data.id);
          }
        });
      }
      // 处理文件数据
      const arr1 = [];
      if (maintenanceMaterialList?.length !== 0) {
        maintenanceMaterialList?.forEach(item => {
          arr1.push(item.id);
        });
      }
      if (id) {
        await editRecord({
          workOrderId: props.detailData.id,
          ...formValue.value,
          faultImageList: pictureList,
          maintenanceMaterialList: arr1,
          inventoryDetailList
        });
        PxMessage.success("编辑成功");
        // 重置各种状态值
        formValue.value = {
          faultCause: ""
        };
        isSpare.value = undefined;
        recordList.value[index].isEdit = false;
        getList();
      } else {
        await addRecord({
          workOrderId: props.detailData.id,
          ...formValue.value,
          faultImageList: pictureList,
          maintenanceMaterialList: arr1,
          inventoryDetailList
        });
        PxMessage.success("保存成功");
        // 重置各种状态值
        isSpare.value = undefined;
        formValue.value = {
          faultCause: ""
        };
        recordList.value[index].isEdit = false;
        getList();
      }
    }
  });
};

const handleCancel = index => {
  if (formValue.value.id) {
    isCanEdit.value = true;
    recordList.value[index].isEdit = false;
    isSpare.value = false;
    formRef.value[0].resetFields();
    formValue.value.id = "";
    formValue.value.remark = "";
    formValue.value.acceptTime = "";
    formValue.value.sparePartOutNum = "";
    formValue.value.isChange = undefined;
    formValue.value.faultImageList = [];
    formValue.value.maintenanceMaterialList = [];
    formValue.value.sparePartInventoryDTOList = [];
  } else {
    PxMessageBox.confirm(`确认取消吗？取消后内容将不会保存，请谨慎操作`, "提示", {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "warning"
    })
      .then(async () => {
        recordList.value.splice(recordList.value.length - 1, 1);
        isCanEdit.value = true;
        formRef.value[0].resetFields();
        isSpare.value = false;
        formValue.value.id = "";
        formValue.value.remark = "";
        formValue.value.acceptTime = "";
        formValue.value.sparePartOutNum = "";
        formValue.value.isChange = undefined;
        formValue.value.faultImageList = [];
        formValue.value.maintenanceMaterialList = [];
        formValue.value.sparePartInventoryDTOList = [];
      })
      .catch(() => {
        isCanEdit.value = true;
      });
  }
};
</script>

<style lang="scss" scoped>
@import url("@/views/erc/scss/table-list.scss");

.equip-wrap-common {
  height: auto;
  padding: 0;
}

.view-order-item {
  display: flex;
  flex-direction: row;
  align-items: flex-start;
  margin-bottom: 10px;
  font-size: 14px;

  .title {
    width: 150px;
    line-height: 32px;
    color: rgb(0 0 0 / 80%);
    text-align: right;
  }

  .content {
    flex: 1;
    font-weight: 600;
    line-height: 32px;
    color: rgb(0 0 0 / 90%);
  }
}
</style>
